package com.project.bo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.project.bean.Role;
import com.project.persistence.dao.RoleDAOImpl;
import com.project.utils.Utils;

public class RoleBO {
	//TODO implementar logs
	
	private static HashMap<Integer,Role> roles = new HashMap<Integer, Role>();
	private static RoleBO instance;
	
	public static RoleBO getInstance() {
		if (instance == null) {
			instance = new RoleBO();
		}
		return instance;
	}
	
	private RoleBO(){
		
	}
	
	public List<Role> getRoles(){
		
		if (roles == null || roles.size() <= 0) {
			RoleDAOImpl roleDAO = new RoleDAOImpl();
			List<Role> listResult = roleDAO.getAll();
			
			for(Role role :  listResult) {
				FeaturesBO featuresBO = FeaturesBO.getInstance();
				role.setFeatures(featuresBO.getFeaturesByRoleId(role.getRoleId()));
				
				insertOnCache(role);
			}
		} 
		
		return new ArrayList<Role>(roles.values());
	}
	
	public Boolean insert(Role role) {
		RoleDAOImpl roleDAO = new RoleDAOImpl();
		Boolean result = roleDAO.insert(role);
		
		if (result) {
			insertOnCache(role);
		}
		
		return result;
	}
	
	public Boolean disable(Integer roleId) {
		Role role = new Role();
		
		role = roles.get(roleId);
		role.setActive(Boolean.FALSE);
		
		RoleDAOImpl roleDAO = new RoleDAOImpl();
		Boolean result = roleDAO.disable(role);
		
		if (result) {
			insertOnCache(role);
		}
		
		return result;
	}
	
	public Boolean enable(Integer roleId) {
		Role role = new Role();

		role = roles.get(roleId);
		role.setActive(Boolean.TRUE);
		
		RoleDAOImpl roleDAO = new RoleDAOImpl();
		Boolean result = roleDAO.enable(role);
		
		if (result) {
			insertOnCache(role);
		}
		
		return result;
	}
	
	public Boolean update(Role role) {
		RoleDAOImpl roleDAO = new RoleDAOImpl();
		
		Boolean result = roleDAO.update(role);
		
		if(result) {
			role.setFeatures(FeaturesBO.getInstance().getFeaturesByRoleId(role.getRoleId()));
			insertOnCache(role);
		}
		
		return result;
	}
	
	private void insertOnCache(Role role) {
		if (roles != null) {
			roles.put(role.getRoleId(), role);
		}
		Utils.clearUserCache();
	}
	
	public static void clearCache() {
		roles.clear();
		roles = null;
		roles = new HashMap<Integer, Role>();
	}
	
	public static void initializeCache() {
		RoleBO.getInstance().getRoles();
	}
	
	public Role getBoleById(Integer roleId) {
		
		if (roles == null || roles.size() <= 0) {
			initializeCache();
		}
		
		return roles.get(roleId);
	}
}
